/**
 * Copyright 2021 xpstem.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.xpstem.lelink.command;

import com.xpstem.lelink.enums.CommandCode;
import com.xpstem.lelink.enums.CommandType;
import com.xpstem.lelink.type.Data16;
import com.xpstem.lelink.type.Data8;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * EV3 system command package
 * @author billy zhang
 */
public class EV3SystemCommandPackage implements EV3CommandPackage {

    private CommandType commandType;
    private CommandCode commandCode;
    private int counter;
    /**
     * 命令请求数据
     */
    private byte[] payload;

    public EV3SystemCommandPackage(CommandType commandType, CommandCode commandCode, byte[] payload) {
        this.commandCode = commandCode;
        this.commandType = commandType;
        this.payload = payload;
    }

    @Override
    public void setCounter(int counter) {
        this.counter = counter;
    }

    @Override
    public byte[] getPackage() throws IOException {

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        Data16.from(counter).writeTo(outputStream);
        Data8.from(commandType.value()).writeTo(outputStream);
        Data8.from(commandCode.value()).writeTo(outputStream);

        outputStream.write(payload);

        return outputStream.toByteArray();
    }
}
